package cn.tedu.egweibo06.controller;

import cn.tedu.egweibo06.common.response.JsonResult;
import cn.tedu.egweibo06.common.response.StatusCode;
import cn.tedu.egweibo06.mapper.UserMapper;
import cn.tedu.egweibo06.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo06.pojo.dto.UserRegDTO;
import cn.tedu.egweibo06.pojo.entity.User;
import cn.tedu.egweibo06.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("用户注册")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO) {
        log.debug("userRegDTO = " + userRegDTO);
        String username = userRegDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);
        if (userVO != null){
            return JsonResult.fail(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }
    @ApiOperation("用户登录")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        log.debug("userLoginDTO = " + userLoginDTO);
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        UserVO userVO = userMapper.selectByUser(username,password);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        log.debug("userVO = " + userVO);
        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }
    @ApiOperation("获取当前用户")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }
    @ApiOperation("退出登录")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
    }

}
